package com.bookcloud.java21.chapter4.继承Object类413;

public class Person {
  private String name;
  private int age;

  public Person() {}

  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
  }

  @Override
  protected Object clone() throws CloneNotSupportedException {
    return super.clone();
  }

  @Override
  public boolean equals(Object obj) {
    // 先判断是否是同一个对象
    if (obj == null || getClass() != obj.getClass()) return false; // 类型不同

    Person person = (Person) obj; // 类型转换
    return age == person.age && name.equals(person.name);
  }

  @Override
  public int hashCode() {
    // 重写hashcode
    int hash = 17;
    hash = hash * 31 + name.hashCode();
    hash = hash * 31 + age;
    return hash;
  }

  public static void main(String[] args) {
    Person p1 = new Person("张三", 18);
    System.out.println("打印出p1:" + p1);
    Person p2 = new Person("李四", 18);
    System.out.println(p1.equals(p2));
    // 打印出p1和p2的地址
    System.out.println("p1的地址:" + p1.hashCode());
    System.out.println("p2的地址:" + p2.hashCode());
  }
}
